#!/bin/bash

# 企业微信H5应用快速部署脚本
# 使用方法: ./deploy-wechat-h5.sh your-domain.com

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查参数
if [ $# -eq 0 ]; then
    echo -e "${RED}错误: 请提供域名参数${NC}"
    echo "使用方法: $0 your-domain.com"
    exit 1
fi

DOMAIN=$1
API_DIR="/opt/refund-api"
WEB_DIR="/var/www/refund-h5"

echo -e "${GREEN}开始部署企业微信H5应用到域名: $DOMAIN${NC}"

# 1. 更新系统
echo -e "${YELLOW}1. 更新系统包...${NC}"
sudo apt update && sudo apt upgrade -y

# 2. 安装必要软件
echo -e "${YELLOW}2. 安装必要软件...${NC}"
sudo apt install -y nginx certbot python3-certbot-nginx curl wget

# 3. 安装.NET 6.0 Runtime
echo -e "${YELLOW}3. 安装.NET 6.0 Runtime...${NC}"
wget https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
sudo apt update
sudo apt install -y aspnetcore-runtime-6.0

# 4. 创建目录
echo -e "${YELLOW}4. 创建应用目录...${NC}"
sudo mkdir -p $API_DIR
sudo mkdir -p $WEB_DIR
sudo mkdir -p /opt/scripts
sudo mkdir -p /opt/backups

# 5. 设置权限
echo -e "${YELLOW}5. 设置目录权限...${NC}"
sudo chown -R www-data:www-data $API_DIR
sudo chown -R www-data:www-data $WEB_DIR

# 6. 创建systemd服务文件
echo -e "${YELLOW}6. 创建systemd服务...${NC}"
sudo tee /etc/systemd/system/refund-api.service > /dev/null <<EOF
[Unit]
Description=Refund API Service
After=network.target

[Service]
Type=notify
WorkingDirectory=$API_DIR
ExecStart=/usr/bin/dotnet $API_DIR/Lzfy_Refund_Service.dll
Restart=always
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=refund-api
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target
EOF

# 7. 申请SSL证书
echo -e "${YELLOW}7. 申请SSL证书...${NC}"
sudo certbot certonly --nginx -d $DOMAIN --non-interactive --agree-tos --email admin@$DOMAIN

# 8. 创建Nginx配置
echo -e "${YELLOW}8. 创建Nginx配置...${NC}"
sudo tee /etc/nginx/sites-available/refund-h5 > /dev/null <<EOF
server {
    listen 80;
    server_name $DOMAIN;
    return 301 https://\$server_name\$request_uri;
}

server {
    listen 443 ssl http2;
    server_name $DOMAIN;

    # SSL证书配置
    ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    # 安全头
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # 企业微信访问限制
    set \$allowed 0;
    if (\$http_user_agent ~* "wxwork|MicroMessenger") {
        set \$allowed 1;
    }
    # 开发调试时可以注释下面3行
    if (\$allowed = 0) {
        return 403 "Access denied. Please access through WeChat Work.";
    }

    # 前端静态文件
    location / {
        root $WEB_DIR;
        index index.html;
        try_files \$uri \$uri/ /index.html;
        
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
    }

    # API代理
    location /api/ {
        proxy_pass http://localhost:5000/api/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection keep-alive;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_cache_bypass \$http_upgrade;
        
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }

    client_max_body_size 10M;
    
    # Gzip压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;

    access_log /var/log/nginx/refund-h5.access.log;
    error_log /var/log/nginx/refund-h5.error.log;
}
EOF

# 9. 启用Nginx站点
echo -e "${YELLOW}9. 启用Nginx站点...${NC}"
sudo ln -sf /etc/nginx/sites-available/refund-h5 /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

# 10. 创建监控脚本
echo -e "${YELLOW}10. 创建监控脚本...${NC}"
sudo tee /opt/scripts/monitor-refund.sh > /dev/null <<'EOF'
#!/bin/bash

LOG_FILE="/var/log/refund-monitor.log"

# 检查API服务状态
if ! systemctl is-active --quiet refund-api; then
    echo "$(date): Refund API service is down, restarting..." >> $LOG_FILE
    systemctl restart refund-api
fi

# 检查Nginx状态
if ! systemctl is-active --quiet nginx; then
    echo "$(date): Nginx is down, restarting..." >> $LOG_FILE
    systemctl restart nginx
fi

# 检查SSL证书有效期
if [ -f "/etc/letsencrypt/live/$DOMAIN/cert.pem" ]; then
    cert_days=$(openssl x509 -in /etc/letsencrypt/live/$DOMAIN/cert.pem -noout -dates | grep notAfter | cut -d= -f2 | xargs -I {} date -d {} +%s)
    current_days=$(date +%s)
    days_left=$(( (cert_days - current_days) / 86400 ))

    if [ $days_left -lt 30 ]; then
        echo "$(date): SSL certificate expires in $days_left days" >> $LOG_FILE
    fi
fi
EOF

sudo chmod +x /opt/scripts/monitor-refund.sh

# 11. 设置定时任务
echo -e "${YELLOW}11. 设置定时任务...${NC}"
(sudo crontab -l 2>/dev/null; echo "*/5 * * * * /opt/scripts/monitor-refund.sh") | sudo crontab -

# 12. 创建备份脚本
echo -e "${YELLOW}12. 创建备份脚本...${NC}"
sudo tee /opt/scripts/backup-app.sh > /dev/null <<EOF
#!/bin/bash

DATE=\$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/opt/backups"

# 备份应用文件
tar -czf \$BACKUP_DIR/refund-app_\$DATE.tar.gz $API_DIR $WEB_DIR

# 清理30天前的备份
find \$BACKUP_DIR -name "refund-app_*.tar.gz" -mtime +30 -delete

echo "\$(date): Application backup completed: refund-app_\$DATE.tar.gz" >> /var/log/refund-backup.log
EOF

sudo chmod +x /opt/scripts/backup-app.sh

# 13. 设置每日备份
(sudo crontab -l 2>/dev/null; echo "0 2 * * * /opt/scripts/backup-app.sh") | sudo crontab -

# 14. 配置防火墙
echo -e "${YELLOW}13. 配置防火墙...${NC}"
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw --force enable

echo -e "${GREEN}基础环境部署完成！${NC}"
echo ""
echo -e "${YELLOW}接下来需要手动完成以下步骤：${NC}"
echo ""
echo "1. 上传后端应用文件到: $API_DIR"
echo "   - 在开发机器上运行: dotnet publish -c Release -o ./publish"
echo "   - 上传publish文件夹内容到服务器"
echo ""
echo "2. 配置appsettings.json文件"
echo "   - 数据库连接字符串"
echo "   - 企业微信配置信息"
echo ""
echo "3. 上传前端文件到: $WEB_DIR"
echo "   - 修改前端API配置为: https://$DOMAIN/api"
echo "   - 运行: npm run build"
echo "   - 上传dist文件夹内容到服务器"
echo ""
echo "4. 启动服务:"
echo "   sudo systemctl daemon-reload"
echo "   sudo systemctl enable refund-api"
echo "   sudo systemctl start refund-api"
echo ""
echo "5. 企业微信应用配置:"
echo "   - 应用主页: https://$DOMAIN"
echo "   - 可信域名: $DOMAIN"
echo ""
echo -e "${GREEN}部署脚本执行完成！${NC}"
echo -e "${YELLOW}访问地址: https://$DOMAIN${NC}"